/**
 * 简单的Redis模拟实现，使用Map作为内存存储
 */
class RedisClient {
    constructor() {
        this.store = new Map();
        this.timeouts = new Map();
    }

    /**
     * 设置键值对
     * @param {string} key - 键
     * @param {string} value - 值
     * @param {string} [flag=''] - 标志（如'EX'）
     * @param {number} [expiry=0] - 过期时间（秒）
     */
    async set(key, value, flag = '', expiry = 0) {
          if (typeof key !== 'string' || !key.trim()) {
            throw new Error('Invalid key provided to Redis set');
        }
        this.store.set(key, value);
        // 处理过期时间
        if (flag === 'EX' && expiry > 0) {
            // 清除已存在的超时
            if (this.timeouts.has(key)) {
                clearTimeout(this.timeouts.get(key));
            }
            
            // 设置新的超时
            const timeout = setTimeout(() => {
                this.store.delete(key);
                this.timeouts.delete(key);
            }, expiry * 1000);
            
            this.timeouts.set(key, timeout);
        }
    }

    /**
     * 获取键值
     * @param {string} key - 键
     * @returns {string|null} 值
     */
    async get(key) {
        return this.store.get(key) || null;
    }

    /**
     * 删除键
     * @param {string} key - 键
     */
    async del(key) {
        this.store.delete(key);
        if (this.timeouts.has(key)) {
            clearTimeout(this.timeouts.get(key));
            this.timeouts.delete(key);
        }
    }
}

class Redis {
    static instance = null;

    /**
     * 获取Redis客户端实例
     * @returns {RedisClient}
     */
    static getClient() {
        if (!Redis.instance) {
            Redis.instance = new RedisClient();
        }
        return Redis.instance;
    }
}

export { Redis };